package com.example.voiceassistant.dialog;

import com.example.voiceassistant.asr.AsrStreamingEngine;
import com.example.voiceassistant.audio.AudioFrameListener;
import com.example.voiceassistant.config.ConfigManager;
import com.example.voiceassistant.monitoring.MonitoringService;
import com.example.voiceassistant.tts.TtsEngine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.Duration;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 会话管理器，负责维护对话状态与超时控制。
 * IDLE状态：仅监听唤醒词；ACTIVE状态：支持连续语音交互。
 * 超时后切换回IDLE，程序不结束，继续常驻监听。
 */
public class DialogSessionManager implements AudioFrameListener, AsrStreamingEngine.RecognitionCallback {

    private static final Logger LOGGER = LoggerFactory.getLogger(DialogSessionManager.class);

    private final AsrStreamingEngine asrStreamingEngine;
    private final TtsEngine ttsEngine;
    private final MonitoringService monitoringService;

    private final AtomicBoolean active = new AtomicBoolean(false);
    private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
    private final Duration timeout;

    private ScheduledFuture<?> timeoutFuture;

    public DialogSessionManager(ConfigManager configManager,
                                MonitoringService monitoringService,
                                AsrStreamingEngine asrStreamingEngine,
                                TtsEngine ttsEngine) {
        this.monitoringService = monitoringService;
        this.asrStreamingEngine = asrStreamingEngine;
        this.ttsEngine = ttsEngine;
        this.timeout = Duration.ofSeconds(configManager.getDialogTimeoutSeconds());
    }

    public void onWakeWordDetected(String wakeWord) {
        if (active.compareAndSet(false, true)) {
            monitoringService.event("dialog.started", "wakeWord=" + wakeWord);
            ttsEngine.speak("我在，很高兴为您服务");
            scheduleTimeout();
        } else {
            LOGGER.info("会话已激活，忽略重复唤醒。");
            scheduleTimeout();
        }
    }

    @Override
    public void onAudioData(byte[] data) {
        if (!active.get()) {
            return; // IDLE时不处理，留给WakeWordDetector
        }
        System.out.println("Dialog received audio data, length: " + data.length); // Debug
        scheduleTimeout();
        asrStreamingEngine.processAudioData(data, this);
    }

    @Override
    public void onRecognized(String text, String aiReply) {
        monitoringService.counter("dialog.turn.completed").increment();
        LOGGER.info("识别文本: {}", text);
        System.out.println("Final recognized text: " + text); // Debug: 最终识别文本
        System.out.println("AI reply: " + aiReply); // Debug: AI回复
        ttsEngine.speak(aiReply);
    }

    @Override
    public void onError(Throwable throwable) {
        monitoringService.counter("dialog.turn.error").increment();
        LOGGER.error("对话轮次处理失败", throwable);
        ttsEngine.speak("当前处理遇到问题，请稍后再试。");
    }

    private void scheduleTimeout() {
        if (timeoutFuture != null) {
            timeoutFuture.cancel(false);
        }
        timeoutFuture = scheduler.schedule(this::expireSession, timeout.toMillis(), TimeUnit.MILLISECONDS);
    }

    /**
     * 超时后切换回IDLE，程序不结束，继续常驻监听。
     */
    private void expireSession() {
        if (active.compareAndSet(true, false)) {
            monitoringService.event("dialog.ended", "timeout");
            ttsEngine.speak("已退出对话，请说‘AI管家’唤醒我继续服务。");
        }
    }

    public void shutdown() {
        expireSession();
        scheduler.shutdownNow();
    }
}

